package com.samuel.igoodman.web.base;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.samuel.igoodman.entity.account.Userinfo;

@SuppressWarnings("serial")
public class BaseAction extends ActionSupport {

	protected String op; // 操作符号
	protected String message; // 传递到下个页面的消息
	public final String HOME = "home"; // 主页
	public final String DETAIL = "detail"; // 详情

	protected int pageNo = 1; // 页码
	protected int pageSize = 10; // 大小

	public BaseAction() {
		op = "";
		message = "";
	}

	public Object getSessionAttribute(String name) {
		return ServletActionContext.getRequest().getSession()
				.getAttribute(name);
	}

	public void setSessionAttribute(String name, Object value) {
		ServletActionContext.getRequest().getSession()
				.setAttribute(name, value);
	}

	public void setRequestAtt(String name, Object v) {
		ServletActionContext.getRequest().setAttribute(name, v);
	}

	public String getRequestParameter(String name) {
		return ServletActionContext.getRequest().getParameter(name);
	}

	public String[] getParameterValues(String name) {
		HttpServletRequest req = ServletActionContext.getRequest();
		return req.getParameterValues(name);
	}

	public String getRealPath(String path) {
		ActionContext context = ActionContext.getContext();
		ServletContext servletContext = (ServletContext) context
				.get(ServletActionContext.SERVLET_CONTEXT);
		return servletContext.getRealPath(path);
	}

	public void addCookie(String name, String value, int expiry) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(expiry);
		ServletActionContext.getResponse().addCookie(cookie);
	}

	public String getCookie(String name) {
		Cookie[] cookies = ServletActionContext.getRequest().getCookies();
		for (Cookie cookie : cookies) {
			if (name.equals(cookie.getName())) {
				return cookie.getValue();
			}
		}
		return null;
	}

	public Userinfo getCurrUserinfo() {
		return (Userinfo) getSessionAttribute(Userinfo.SESSION_PARAMETER_NAME);
	}

	public String getOp() {
		return op;
	}

	public void setOp(String op) {
		this.op = op;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String getSystemName() {
		return "一起读书吧!";
	}

}
